package com.beiye.drivertransport;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.activity.SplashActivity;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.bean.CheckBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;
import com.githang.statusbar.StatusBarCompat;


import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class LoginActivity extends TwoBaseAty {


    TextView acLoginTvPwd;

    View acLoginViewPwd;

    LinearLayout acLoginLlPwdLogin;

    TextView acLoginTvYzm;

    View acLoginViewYzm;

    LinearLayout acLoginLlYzmLogin;

    EditText acLoginEtMobile;

    EditText acLoginEtPwd;

    ImageView acLoginIvShowPwd;

    EditText acLoginEtYzm;

    TextView acLoginTvSendCode;

    TextView acLoginTvConfirm;

    LinearLayout acLoginLlDriverReg;

    LinearLayout acLoginLlIndustryReg;

    LinearLayout acLoginLlForgetPwd;

    RelativeLayout acLoginRvPwd;

    RelativeLayout acLoginRvYzm;
    private TimeCount time;
    private boolean isPwdVisible;
    private int loginType;
    private AlertDialog dialog;


    @Override
    public void initData() {
        acLoginTvPwd = (TextView) findViewById(R.id.ac_login_tv_pwd);
        acLoginViewPwd = (View) findViewById(R.id.ac_login_view_pwd);
        acLoginLlPwdLogin = (LinearLayout) findViewById(R.id.ac_login_ll_pwdLogin);
        acLoginTvYzm = (TextView) findViewById(R.id.ac_login_tv_yzm);
        acLoginViewYzm = (View) findViewById(R.id.ac_login_view_yzm);
        acLoginLlYzmLogin = (LinearLayout) findViewById(R.id.ac_login_ll_yzmLogin);
        acLoginEtMobile = (EditText) findViewById(R.id.ac_login_et_mobile);
        acLoginEtPwd = (EditText) findViewById(R.id.ac_login_et_pwd);
        acLoginIvShowPwd = (ImageView) findViewById(R.id.ac_login_iv_showPwd);
        acLoginEtYzm = (EditText) findViewById(R.id.ac_login_et_yzm);
        acLoginTvSendCode = (TextView) findViewById(R.id.ac_login_tv_sendCode);
        acLoginTvConfirm = (TextView) findViewById(R.id.ac_login_tv_confirm);
        acLoginLlDriverReg = (LinearLayout) findViewById(R.id.ac_login_ll_driverReg);
        acLoginLlIndustryReg = (LinearLayout) findViewById(R.id.ac_login_ll_industryReg);
        acLoginLlForgetPwd = (LinearLayout) findViewById(R.id.ac_login_ll_forgetPwd);
        acLoginRvPwd = (RelativeLayout) findViewById(R.id.ac_login_rv_pwd);
        acLoginRvYzm = (RelativeLayout) findViewById(R.id.ac_login_rv_yzm);

        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#ffffff"));
        time = new TimeCount(60000, 1000);
        if (UserManger.isLogin()) {
            Intent intent = new Intent(LoginActivity.this, SplashActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void requestData() {

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    public void onClick(View view) {

        String mobile = getEtData(acLoginEtMobile);
        String pwd = getEtData(acLoginEtPwd);
        String yzm = getEtData(acLoginEtYzm);

        int id = view.getId();
        if (id == R.id.ac_login_ll_pwdLogin) {//密码选项卡
            loginType = 0;
            acLoginTvPwd.setTextColor(getResources().getColor(R.color.theme));
            acLoginTvYzm.setTextColor(getResources().getColor(R.color.black_p50));
            acLoginViewPwd.setBackgroundColor(getResources().getColor(R.color.theme));
            acLoginViewPwd.setVisibility(View.VISIBLE);
            acLoginViewYzm.setVisibility(View.INVISIBLE);
            acLoginRvPwd.setVisibility(View.VISIBLE);
            acLoginRvYzm.setVisibility(View.GONE);

            InputFilter[] filters = {new InputFilter.LengthFilter(18)};
            acLoginEtMobile.setFilters(filters);
            acLoginEtMobile.setHint("请输入手机号或身份证号");
        } else if (id == R.id.ac_login_ll_yzmLogin) {//验证码选项卡
            loginType = 1;
            acLoginTvPwd.setTextColor(getResources().getColor(R.color.black_p50));
            acLoginTvYzm.setTextColor(getResources().getColor(R.color.theme));
            acLoginViewYzm.setBackgroundColor(getResources().getColor(R.color.theme));
            acLoginViewPwd.setVisibility(View.INVISIBLE);
            acLoginViewYzm.setVisibility(View.VISIBLE);
            acLoginRvPwd.setVisibility(View.GONE);
            acLoginRvYzm.setVisibility(View.VISIBLE);

            InputFilter[] filters1 = {new InputFilter.LengthFilter(11)};
            acLoginEtMobile.setFilters(filters1);
            acLoginEtMobile.setHint("请输入手机号");
        } else if (id == R.id.ac_login_iv_showPwd) {//显示密码
//修改密码是否可见的状态
            isPwdVisible = !isPwdVisible;
//設置密碼是否可見
            if (isPwdVisible) {
//设置密码为明文，并更改眼睛图标
                acLoginEtPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                acLoginIvShowPwd.setImageResource(R.mipmap.mingpassword);
            } else {
//设置密码为暗文，并更改眼睛图标
                acLoginEtPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                acLoginIvShowPwd.setImageResource(R.mipmap.yincangpassword);
            }
//设置光标位置的代码需放在设置明暗文的代码后面
            acLoginEtPwd.setSelection(pwd.length());
        } else if (id == R.id.ac_login_tv_sendCode) {//发送短信验证码
            if (Utils.isFastClicker()) {
                return;
            }
            if (!isPanduan1(mobile)) {
                return;
            }
            time.start();// 开始计时
            new Login().getCode(mobile, 6, this, 2);
        } else if (id == R.id.ac_login_tv_confirm) {//提交信息
            if (Utils.isFastClicker()) {
                return;
            }
            if (mobile.isEmpty()) {
                Toast.makeText(getApplicationContext(), "请输入手机号或身份证号", Toast.LENGTH_SHORT).show();
            } else {
                if (loginType == 0) {
                    if (pwd.isEmpty()) {
                        Toast.makeText(getApplicationContext(), "请输入密码", Toast.LENGTH_SHORT).show();
                    } else {
                        showLoadingDialog("正在登录");
                        setHasAnimiation(false);
                        new Login().pLogin(mobile, pwd, this, 1);
                    }
                } else if (loginType == 1) {
                    if (yzm.isEmpty()) {
                        Toast.makeText(getApplicationContext(), "请输入验证码", Toast.LENGTH_SHORT).show();
                    } else {
                        showLoadingDialog("正在登录");
                        setHasAnimiation(false);
                        new Login().pLogincode(mobile, yzm, 1, this, 3);
                    }
                }
            }
        } else if (id == R.id.ac_login_ll_driverReg) { //驾驶员注册
            if (Utils.isFastClicker()) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            View view1 = View.inflate(LoginActivity.this, R.layout.diolog_regis_layout, null);
            TextView btn_gone = (TextView) view1.findViewById(R.id.positiveButton);
            TextView driverbtn = (TextView) view1.findViewById(R.id.message);
            TextView individualbtn = (TextView) view1.findViewById(R.id.message1);
            dialog = builder.create();
            dialog.show();
            dialog.getWindow().setContentView(view1);
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            dialog.setCancelable(true);
            btn_gone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                }
            });
            driverbtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    //startActivityForResult(DriverRegistrationActivity.class, null, 0);
                }
            });
            individualbtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    //startActivityForResult(IndividualRegistrationActivity.class, null, 1);
                }
            });
        } else if (id == R.id.ac_login_ll_industryReg) {//行业人员注册
            //startActivity(IndustrypersonnelRegisterActivity.class, null);
            //忘记密码
        } else if (id == R.id.ac_login_ll_forgetPwd) {
            if (Utils.isFastClicker()) {
                return;
            }
            //startActivity(ForgetPasswordActivity.class, null);
        }
    }


    //倒计时定时器
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            acLoginTvSendCode.setText("重新发送");
            acLoginTvSendCode.setClickable(true);
//  sent_code.setTextColor(Color.BLACK);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            acLoginTvSendCode.setClickable(false);//防止重复点击
            acLoginTvSendCode.setText("重新发送" + "(" + millisUntilFinished / 1000 + "s" + ")");
//  sent_code.setTextColor(Color.WHITE);
        }
    }

    public String getEtData(EditText et) {
        return et.getText().toString().trim();
    }

    private boolean isPanduan1(String cellphone1) {
//判断是账号否为空
        if (TextUtils.isEmpty(cellphone1)) {
            Toast.makeText(LoginActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
            return false;
        }
//判断是否符合正则表达式
        boolean checkMobileNumberr = Utils.isMobile(cellphone1);

        if (!checkMobileNumberr) {
            Toast.makeText(LoginActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        super.onSuccess(result, call, response, what);

        Intent intent = new Intent(this, SplashActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        LoginUserBean loginUserBean = JSON.parseObject(result, LoginUserBean.class);
        UserManger.setUserInfo(loginUserBean);//保存用户信息

        switch (what) {
            case 1://密码登录
                dismissLoadingDialog();
                UserManger.setIsLogin(true);
                startActivity(intent);
                finish();
                break;
            case 2://发送验证码
                CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
                int code = checkBean.getCode();
                if (code == 0) {
                    Toast.makeText(LoginActivity.this, "获取验证码成功", Toast.LENGTH_SHORT).show();
                }
                break;
            case 3://验证码登录
                dismissLoadingDialog();
                UserManger.setIsLogin(true);
                startActivity(intent);
                finish();
                break;
        }
    }

    @Override
    public void onError(String result, Call call, Response response, int what) {
        super.onError(result, call, response, what);

        switch (what) {
            case 1:
                Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                break;
            case 2:
                break;
            case 3:
                Toast.makeText(LoginActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        time.cancel();
    }
}